import '../models/check_in_goal.dart';
import '../services/web_database_service.dart';

class CheckInGoalRepository {
  final WebDatabaseService _dbService = WebDatabaseService();
  static const String _tableName = WebDatabaseService.checkInGoalsTable;

  /// 添加签到目标
  Future<int> addCheckInGoal(CheckInGoal goal) async {
    try {
      print('CheckInGoalRepository: 开始添加签到目标: ${goal.title}');
      final data = goal.toMap();
      data.remove('id'); // 移除id，让数据库自动生成
      print('CheckInGoalRepository: 处理后的数据: $data');
      final result = await _dbService.insert(_tableName, data);
      print('CheckInGoalRepository: 添加签到目标结果，返回ID: $result');
      
      if (result < 0) {
        print('CheckInGoalRepository: 添加签到目标失败，返回ID为负数');
        throw Exception('添加签到目标失败，数据库操作错误');
      }
      
      return result;
    } catch (e, stackTrace) {
      print('CheckInGoalRepository: 添加签到目标失败: $e');
      print('CheckInGoalRepository: 错误堆栈: $stackTrace');
      rethrow;
    }
  }

  /// 获取所有签到目标
  Future<List<CheckInGoal>> getAllCheckInGoals() async {
    final results = await _dbService.getAll(_tableName);
    return results.map((data) => CheckInGoal.fromMap(data)).toList();
  }

  /// 获取所有激活的签到目标
  Future<List<CheckInGoal>> getActiveCheckInGoals() async {
    try {
      print('CheckInGoalRepository: 获取所有激活的签到目标');
      final results = await _dbService.getAll(_tableName);
      print('CheckInGoalRepository: 获取到 ${results.length} 条记录');
      final activeGoals = results
          .where((data) => data['is_active'] == 1)
          .map((data) => CheckInGoal.fromMap(data))
          .toList();
      print('CheckInGoalRepository: 筛选出 ${activeGoals.length} 条激活的目标');
      return activeGoals;
    } catch (e, stackTrace) {
      print('CheckInGoalRepository: 获取激活目标失败: $e');
      print('CheckInGoalRepository: 错误堆栈: $stackTrace');
      return [];
    }
  }

  /// 根据ID获取签到目标
  Future<CheckInGoal?> getCheckInGoalById(int id) async {
    final result = await _dbService.getById(_tableName, id);
    return result != null ? CheckInGoal.fromMap(result) : null;
  }

  /// 更新签到目标
  Future<void> updateCheckInGoal(CheckInGoal goal) async {
    if (goal.id == null) return;
    
    final updatedGoal = goal.copyWith(
      updatedAt: DateTime.now().millisecondsSinceEpoch,
    );
    
    await _dbService.update(_tableName, updatedGoal.toMap());
  }

  /// 删除签到目标
  Future<void> deleteCheckInGoal(int id) async {
    await _dbService.delete(_tableName, id);
  }

  /// 激活/停用签到目标
  Future<void> toggleGoalActive(int id, bool isActive) async {
    final goal = await getCheckInGoalById(id);
    if (goal == null) return;
    
    final updatedGoal = goal.copyWith(
      isActive: isActive,
      updatedAt: DateTime.now().millisecondsSinceEpoch,
    );
    
    await _dbService.update(_tableName, updatedGoal.toMap());
  }

  /// 获取签到目标数量
  Future<int> getCheckInGoalCount() async {
    return await _dbService.count(_tableName);
  }

  /// 清空所有签到目标
  Future<void> clearAllCheckInGoals() async {
    await _dbService.clearTable(_tableName);
  }
}